package com.uzhie.util;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.executable.ExecutableValidator;
import java.lang.reflect.Method;
import java.util.Set;

/**
 * @author TangFei
 *         <p>
 *         Created by TangFei on 2018/3/26.
 *         </p>
 * @since jdk
 */
public class ValidateUtil {
    public static <T> String validate(T entity) {
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        Set<ConstraintViolation<T>> violations = validator.validate(entity);
        if (violations.size() == 0) {
            return null;
        } else {
            StringBuffer buf = new StringBuffer();
            int i = 1;
            for (ConstraintViolation<T> violation : violations) {
                buf.append(i + ":");
                buf.append(violation.getMessage() + "<BR>\n");
                i++;
            }
            return buf.toString();
        }
    }

    public static <T> String validateAll(T obj, Method method, Object[] parameterValues) {
        // 获取验证器
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        ExecutableValidator executableValidator = validator.forExecutables();
        Set<ConstraintViolation<T>> methodValidators = executableValidator.validateParameters(obj, method, parameterValues);
        StringBuffer buf = new StringBuffer();
        if (methodValidators.size() > 0) {
            int i = 1;
            for (ConstraintViolation<T> violation : methodValidators) {
                buf.append(i + ":");
                buf.append(violation.getMessage() + "\n");
                i++;
            }
        }
        return buf.toString();
    }

    /**
     * 校验参数 获取到第一个校验信息就返回
     *
     * @param obj
     * @param method
     * @param parameterValues
     * @param <T>
     * @return
     */
    public static <T> String validateOne(T obj, Method method, Object[] parameterValues) {
        // 获取验证器
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        ExecutableValidator executableValidator = validator.forExecutables();
        Set<ConstraintViolation<T>> methodValidators = executableValidator.validateParameters(obj, method, parameterValues);
        String msg = "";
        if (methodValidators.size() > 0) {
            msg = methodValidators.iterator().next().getMessage();
        }
        return msg;
    }

}
